<template>
  <el-dialog v-bind="settings" :visible.sync="settings.visible" @open="open">
    <div id="code-container" />
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { loginApi } from '@/api/api.js'

export default {
  data() {
    return {
      appId: '',
      loginUrl: '',
      redirectUri: '',
      settings: {
        visible: false,
        unbandFlag: false
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    open() {
      this.init()
    },
    async init() {
      await this._getDingTalkInfo()
      this._dingTalkLogin()
    },
    // 获取钉钉前置数据
    async _getDingTalkInfo() {
      const { data } = await this.$request(loginApi.getDingTalkInfo)
      this.appId = data.appId
      this.loginUrl = data.loginUrl + encodeURIComponent('#/usercenter')
      // this.loginUrl = 'https://oapi.dingtalk.com/connect/qrconnect?appid=dingoaupbsbpj7swwm7laz&response_type=code&scope=snsapi_login&state=dingtalk&redirect_uri=http://127.0.0.1:8080/' + encodeURIComponent('#/usercenter')

      this.redirectUri = data.redirectUri + encodeURIComponent('#/usercenter')
      // this.redirectUri = 'http://127.0.0.1:8080/' + encodeURIComponent('#/usercenter')
    },
    // 绑定
    async _dingTalkLogin() {
      const _this = this
      window.DDLogin({
        id: 'code-container',
        // goto这里需要对url整体做一个urlencode编码
        goto: encodeURIComponent(_this.loginUrl),
        style: 'border:none;background-color:#FFFFFF;',
        width: '100%',
        height: '300'
      })

      let state = this.settings.unbandFlag ? 'unbindDingtalk' : 'dingtalk'

      let handleMessage = function (event) {
        let origin = event.origin
        if (origin == 'https://login.dingtalk.com') {
          //判断是否来自ddLogin扫码事件。
          let loginTmpCode = event.data

          let url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + _this.appId + '&response_type=code&scope=snsapi_login&state=' + state + '&redirect_uri=' + _this.redirectUri + '&loginTmpCode=' + loginTmpCode + ''
          window.location.href = url
        }
      }
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false)
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 421px;
}
</style>
